Source for file GBFilePicker.module.php

Documentation is available at GBFilePicker.module.php

  1. <?php
  2. #-------------------------------------------------------------------------------
  3. #
  4. # Module : GBFilePicker (c) 2010 by Georg Busch (georg.busch@gmx.net)
  5. #          a filepicker tool for CMS Made Simple
  6. #          The projects homepage is ... ToDo ...
  7. #          CMS Made Simple is (c) 2004-2010 by Ted Kulp
  8. #          The projects homepage is: cmsmadesimple.org
  9. # Version: 1
  10. # File   : GBFilePicker.module.php
  11. # Purpose: initial module class.
  12. # License: GPL
  13. #
  14. #-------------------------------------------------------------------------------
  15.  
  16. class GBFilePicker extends CMSModule {
  17.     
  18.     var $displaySettings;
  19.     var $isAdmin;
  20.     var $header;
  21.     
  22.     function GBFilePicker() {
  23.         parent::CMSModule();
  24.         $this->displaySettings = array();
  25.         $header = false;
  26.         global $CMS_ADMIN_PAGE;
  27.         if(isset($CMS_ADMIN_PAGE) && $CMS_ADMIN_PAGE == 1) {
  28.             global $gCms;
  29.             $userOps       =& $gCms->GetUserOperations();
  30.             $this->isAdmin = $userOps->UserInGroup(get_userid(false),1);
  31.         }
  32.     }
  33.     
  34.     function GetName() {
  35.         return 'GBFilePicker';
  36.     }
  37.     
  38.     function GetFriendlyName() {
  39.         return $this->Lang('GBFilePicker');
  40.     }
  41.     
  42.     function GetVersion() {
  43.         return '1';
  44.     }
  45.     
  46.     function GetHelp() {
  47.         $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'doc' . DIRECTORY_SEPARATOR;
  48.         if(file_exists($path . 'help_' . $this->curlang . '.html'))
  49.             return file_get_contents($path . 'help_' . $this->curlang . '.html');
  50.         else
  51.             return file_get_contents($path . 'help_en_US.html');
  52.     }
  53.     
  54.     function GetAuthor() {
  55.         return 'NaN';
  56.     }
  57.     
  58.     function GetAuthorEmail() {
  59.         return;
  60.     }
  61.     
  62.     function GetChangeLog() {
  63.         $changelog = dirname(__FILE__) . DIRECTORY_SEPARATOR . 
  64.             'doc' . DIRECTORY_SEPARATOR . 'changelog.html';
  65.         if(file_exists($changelog))
  66.             return file_get_contents($changelog);
  67.     }
  68.     
  69.     function IsPluginModule() {
  70.         return true;
  71.     }
  72.     
  73.     function HasAdmin() {
  74.         return true;
  75.     }
  76.     
  77.     function GetAdminSection() {
  78.         return 'extensions';
  79.     }
  80.     
  81.     function GetAdminDescription() {
  82.         return $this->lang('admindescription');
  83.     }
  84.     
  85.     function VisibleToAdminUser() {
  86.         return $this->Checkpermission('Manage GBFilePicker');
  87.     }
  88.     
  89.     function MinimumCMSVersion() {
  90.         return "1.6.8";
  91.     }
  92.     
  93.     function MaximumCMSVersion() {
  94.         return "1.9.9";
  95.     }
  96.     
  97.     function InstallPostMessage() {
  98.         return $this->Lang('postinstall', $this->GetVersion());
  99.     }
  100.     
  101.     function UninstallPostMessage() {
  102.         return $this->Lang('postuninstall', $this->GetVersion());
  103.     }
  104.     
  105.     function UninstallPreMessage() {
  106.         return $this->Lang('confirmuninstall');
  107.     }
  108.     
  109.     function HandlesEvents() {
  110.         return true;
  111.     }
  112.     
  113.     function DoAction($action, $id, $params, $returnid = '') {
  114.         switch($action) {
  115.             case 'defaultadmin':
  116.                 global $gCms;
  117.                 // default (image dropdown)
  118.                 $this->smarty->assign('imagedropdown_text', $this->lang('imagedropdown',str_replace($gCms->config['root_url'],'',$gCms->config['uploads_url']).'/images'));
  119.                 $this->smarty->assign('imagedropdown_input', $this->CreateFilePickerInput($id,'GBFilePicker_image_dropdown','','images'));
  120.                 
  121.                 // image filepicker
  122.                 $this->smarty->assign('imagebrowser_text', $this->lang('imagebrowser',str_replace($gCms->config['root_url'],'',$gCms->config['uploads_url']).'/images'));
  123.                 $this->smarty->assign('imagebrowser_input',$this->CreateFilePickerInput($id, 'GBFilePicker_image_filepicker','','images','','','image','browser'));
  124.                 
  125.                 // file dropdown
  126.                 $this->smarty->assign('filedropdown_text', $this->lang('filedropdown',str_replace($gCms->config['root_url'],'',$gCms->config['uploads_url']).'/'));
  127.                 $this->smarty->assign('filedropdown_input',$this->CreateFilePickerInput($id, 'GBFilePicker_file_dropdown','','','','','file'));
  128.                 
  129.                 // file filepicker
  130.                 $this->smarty->assign('filebrowser_text', $this->lang('filebrowser',str_replace($gCms->config['root_url'],'',$gCms->config['uploads_url']).'/'));
  131.                 $this->smarty->assign('filebrowser_input',$this->CreateFilePickerInput($id, 'GBFilePicker_file_filepicker','','','','','file','browser'));
  132.                 return $this->ProcessTemplate('defaultadmin.tpl');
  133.                 break;
  134.                 
  135.             case 'default':
  136.             case 'savePrefs':
  137.             case 'filePicker':
  138.                 parent::DoAction($action, $id, $params, $returnid);
  139.                 break;
  140.                 
  141.             default: break;
  142.         }
  143.     }
  144.     
  145.     function DoEvent($originator, $eventname, &$params) {
  146.         
  147.     }
  148.     
  149.     function SetParameters() {
  150.         
  151.         $this->RegisterModulePlugin();
  152.         // ToDo: create parameters...
  153.         #$this->RestrictUnknownParams();
  154.         
  155.     }
  156.     
  157.     function HasCapability($capability,$params = array())
  158.     {
  159.         switch( $capability )
  160.         {
  161.             case 'contentblocks':
  162.             case 'content_attributes':
  163.                 return TRUE;
  164.             default:
  165.                 return FALSE;
  166.         }
  167.     }
  168.     
  169.     function GetContentBlockInput($blockName,$value,$params,$adding = false)
  170.     {
  171.         
  172.         // ToDo: Put this in DoAction ?
  173.         // $this->DoAction('default',$id,$params,'');
  174.         $value = $this->CleanUrl($value,false);
  175.         
  176.         $type = 'image';
  177.         if(isset($params['type']))
  178.             $type = strtolower($params['type']);
  179.         
  180.         $fileExt = array();
  181.         if($type == 'image')
  182.             $fileExt = array('jpg','jpeg','gif','png');
  183.         
  184.         if(isset($params['file_extensions']) && $params['file_extensions'] != '') {
  185.             $_fileExt = $this->CleanArray(explode(',',strtolower($params['file_extensions'])));
  186.             if($type == 'image')
  187.                 $_fileExt = $this->CleanArray(array_intersect($_fileExt, $fileExt));
  188.             if(empty($_fileExt))
  189.                 $_fileExt = $fileExt;
  190.             
  191.             $fileExt = $_fileExt;
  192.         }
  193.         
  194.         $excludePrefix = '';
  195.         if(isset($params['exclude_prefix']))
  196.             $excludePrefix = trim($params['exclude_prefix']);
  197.         
  198.         $excludeSufix = '';
  199.         if(isset($params['exclude_sufix']))
  200.             $excludeSufix = trim($params['exclude_sufix']);
  201.         
  202.         $includePrefix = '';
  203.         if(isset($params['include_prefix']))
  204.             $includePrefix = trim($params['include_prefix']);
  205.         
  206.         $includeSufix = '';
  207.         if(isset($params['include_sufix']))
  208.             $includeSufix = trim($params['include_sufix']);
  209.         
  210.         $showSubDirs = $this->isAdmin;
  211.         if(isset($params['show_subdirs']) && $this->IsTrue($params['show_subdirs']))
  212.             $showSubDirs = true;
  213.         
  214.         $mode = 'dropdown';
  215.         if(isset($params['mode']))
  216.             $mode = strtolower($params['mode']);
  217.         
  218.         $dir = '';
  219.         if(isset($params['dir']))
  220.             $dir = $this->CleanUrl($params['dir'],false);
  221.         
  222.         $allowNone = true;
  223.         if(isset($params['allow_none']) && $this->IsFalse($params['allow_none']))
  224.             $allowNone = false;
  225.         
  226.         $lockInput = !$this->isAdmin;
  227.         if(isset($params['lock_input']) && $this->IsFalse($params['lock_input']))
  228.             $lockInput = false;
  229.         
  230.         $addTxt = '';
  231.         if(isset($params['add_txt']))
  232.             $addTxt = trim($params['add_txt']);
  233.         
  234.         $size = '';
  235.         if(isset($params['size']))
  236.             $size = trim($params['size']);
  237.         
  238.         $upload = $delete = $createDirs = $this->CheckPermission('Modify Files');
  239.         $showfm = $this->GetPreference('showfilemanagement', 0);
  240.         if(isset($params['upload']) && $this->IsTrue($params['upload']) && $showfm) {
  241.             $upload = true;
  242.         }
  243.         if(isset($params['delete']) && $this->IsTrue($params['delete']) && $showfm) {
  244.             $delete = true;
  245.         }
  246.         if(isset($params['create_dirs']) && $this->IsTrue($params['create_dirs']) && $showfm) {
  247.             $createDirs = true;
  248.         }
  249.         
  250.         return $this->CreateFilePickerInput('',
  251.             $blockName,
  252.             $value,
  253.             $dir,
  254.             $size,
  255.             '',
  256.             $type,
  257.             $mode,
  258.             $showsubDirs,
  259.             $upload,
  260.             $delete,
  261.             $createDirs,
  262.             $lockInput,
  263.             $fileExt,
  264.             $excludePrefix,
  265.             $includePrefix,
  266.             $excludeSufix,
  267.             $includeSufix,
  268.             $allowNone);
  269.             
  270.     }
  271.     
  272.     
  273.     #function GetNotificationOutput($priority) {
  274.     #    $obj           = new StdClass();
  275.     #    $obj->priority = 3;
  276.     #    $obj->html     = '';
  277.     #    return array($obj);
  278.     #}
  279.     
  280.     #function GetDashboardOutput() {
  281.     #    
  282.     #}
  283.     
  284. /**
  285.  * -----------------------------------------------------------------------------
  286.  * Not part of the module API
  287.  * -----------------------------------------------------------------------------
  288.  */
  289.     
  290.     /**
  291.      * Not part of the module api.
  292.      * Creates the filepicker input.
  293.      *
  294.      * @param string $id - the module id
  295.      * @param string $name - the name of the input field
  296.      * @param string $value - the preselected value
  297.      * @param string $dir - the directory to list the files of (may be relative to uploads dir or absolute path)
  298.      * @param string $addTxt - any additional text that will be added to the html text input when tag is rendered (only works with mode='browser' at the moment)
  299.      * @param string $type - 'image' or 'file'
  300.      * @param string $mode - 'dropdown' or 'browser'
  301.      * @param string $showSubDirs - set to true to show subdirs
  302.      * @param string $upload - set to true to allow file upload
  303.      * @param string $delete - set to true to allow to delete of files and empty subdirs
  304.      * @param string $createDirs - set to true to allow to create subdirs
  305.      * @param string $lockInput - set to false to allow to enter the path to the file
  306.      * @param array|string$fileExt - allowed file extensions (array or csv)
  307.      * @param array|string$excludePrefix - fileprefixes to exclude (array('foo','bar',...) or csv)
  308.      * @param array|string$includePrefix - fileprefixes to include (array('foo','bar',...) or csv)
  309.      * @param array|string$excludeSufix - filesufixes to exclude (array('foo','bar',...) or csv)
  310.      * @param array|string$includeSufix - filesufixes to include (array('foo','bar',...) or csv)
  311.      * @param boolean $allowNone - set to false to hide the option 'none'
  312.      *
  313.      * @return string - the HTML output of the filepicker
  314.      */
  315.     function CreateFilePickerInput($id, $name, 
  316.         $value         = '', 
  317.         $dir           = '', 
  318.         $size          = '', 
  319.         $addTxt        = '', 
  320.         $type          = 'image', 
  321.         $mode          = 'dropdown', 
  322.         $showSubDirs   = false, 
  323.         $upload        = false, 
  324.         $delete        = false, 
  325.         $createDirs    = false, 
  326.         $lockInput     = true, 
  327.         $fileExt       = '', 
  328.         $excludePrefix = '', 
  329.         $includePrefix = '', 
  330.         $excludeSufix  = '', 
  331.         $includeSufix  = '', 
  332.         $allowNone     = true) 
  333.     {
  334.         
  335.         global $gCms;
  336.         
  337.         $showSubDirs = ($this->isAdmin || $this->IsTrue($showSubDirs));
  338.         $upload      = ($this->isAdmin || $this->IsTrue($upload));
  339.         $delete      = ($this->isAdmin || $this->IsTrue($delete));
  340.         $createDirs  = ($this->isAdmin || $this->IsTrue($createDirs));
  341.         $lockInput   = !($this->isAdmin || !$this->IsTrue($lockInput));
  342.         
  343.         if(!is_array($fileExt))
  344.             $fileExt = $this->CleanArray(explode(',',$fileExt));
  345.         
  346.         $_fileExt = array('jpg','jpeg','gif','png');
  347.         if($type == 'image') {
  348.             $fileExt = $this->CleanArray(array_intersect($_fileExt, $fileExt));
  349.             if(empty($fileExt))
  350.                 $fileExt = $_fileExt;
  351.         }
  352.         $fileExt = implode(',',$fileExt);
  353.         
  354.         $thumbnail = '';
  355.         if($type == 'image') {
  356.             $thumbnail = '<br /><span id="'.$id.$name.'_GBFilePickerPreviewImage" class="GBFP_preview">';
  357.             if($value != '') {
  358.                 if(!$thumbURL = $this->GetThumbnail($value, $this->GetPreference('makethumbnail',0),true))
  359.                     $thumbnail = '<img class="GBFP_thumbnail" src="'. $gCms->config['uploads_url'] . '/' . $value . '" width="'.get_site_preference('thumbnail_width',96).'" height="'.get_site_preference('thumbnail_height','auto').'" alt="'.$value.'" title="'.$value.'" /></span>';
  360.                 else
  361.                     $thumbnail = '<img class="GBFP_thumbnail" src="'. $thumbURL. '" alt="'.$value.'" title="'.$value.'" />';
  362.             }
  363.             $thumbnail .= '</span>';
  364.         }
  365.         
  366.         $input = '';
  367.         // ToDo: create function to manipulate head section in frontend to add js and css
  368.         if(!$this->header) {
  369.             $this->smarty->assign('moduleId',$id);
  370.             $input = $this->ProcessTemplate('header.tpl');
  371.             $this->header = true;
  372.         }
  373.         
  374.         if($mode == 'dropdown') {
  375.             $input .= '
  376.                 <span id="'.$id.$name.'_DropdownWrapper">'.
  377.                     $this->CreateFileDropdown($id,$name, 
  378.                         $dir,
  379.                         $value,
  380.                         $excludePrefix, 
  381.                         $includePrefix, 
  382.                         $excludeSufix, 
  383.                         $includeSufix, 
  384.                         $fileExt, 
  385.                         $type, $allowNone).
  386.                 '</span>';
  387.             
  388.             if($upload) {
  389.                 $uploadUrl = $this->CreateLink($id, 'filePicker', '', $this->lang('uploadfile'),array('name' =>$name,'disable_theme'=>true,'subdir'=>($this->isAdmin?$dir:'')),'', true);
  390.                 
  391.                 $input .= '&nbsp;|&nbsp;<input type="button" value="'.$this->lang('uploadfile').'" 
  392.                     id="'.$id.$name.'_GBFP_trigger" class="FilePicker GBFP_trigger" onclick="return false;" href="'.$uploadUrl .'" />';
  393.             }
  394.         }
  395.         else if($mode == 'browser') {
  396.             if($type == 'image') {
  397.                 $input .= '<input id="'.$id.$name.'" type="hidden" name="'.$id.$name.'" value="' . $value . '" />';
  398.             }
  399.             else if($type == 'file') {
  400.                 $input .= '<input id="'.$id.$name.'" type="text"' . ($lockInput?' disabled="disabled"':'') . ($addTxt != ''? ' '.$addTxt.' ':'') . ($size != ''?' size="' . $size . '"':'') . ' name="' . $id.$name . '" value="' . $value . '" />';
  401.             }
  402.             
  403.             $input .= '
  404.                 <input type="button" value="'.$this->lang('select'.$type).'"
  405.                     id="'.$id.$name.'_GBFP_trigger" class="FilePicker GBFP_trigger" onclick="return false;" href="'.
  406.                     $this->CreateLink($id, 'filePicker', '', $this->lang('select'.$type),array('name' =>$name,'disable_theme'=>true,'subdir'=>($this->isAdmin?$dir:'')),'', true).
  407.                 '" />';
  408.             if($allowNone) {
  409.                 $input .= '&nbsp;|&nbsp;<input type="button" value="'.lang('none').'" onclick="jQuery(\'#'.$id.$name.'\').val(\'\'); ToggleThumbnail(\'#'.$id.$name.'_GBFilePickerPreviewImage\',\'\'); return false;" />';
  410.             }
  411.         }
  412.         
  413.         // start session...
  414.         @session_start();
  415.         $_SESSION['GPFP_' . $name] = array(
  416.             'mode'=>$mode,
  417.             'show_subdirs'=>$showSubDirs, 
  418.             'startdir'=>($this->isAdmin?'':$dir), 
  419.             'type'=>$type,
  420.             'value'=>$value,
  421.             'exclude_prefix'=>$excludePrefix,
  422.             'include_prefix'=>$includePrefix,
  423.             'exclude_sufix'=>$excludeSufix,
  424.             'include_sufix'=>$includeSufix,
  425.             'file_extensions'=>$fileExt,
  426.             'upload'=>$upload,
  427.             'delete'=>$delete,
  428.             'create_dirs'=>$createDirs,
  429.             'allow_none'=>$allowNone);
  430.         //
  431.         
  432.         if($gCms->config['debug']) {
  433.             debug_buffer(array(    'mode'=>$mode,
  434.                     'show_subdirs'=>$showSubDirs, 
  435.                     'startdir'=>($this->isAdmin?'':$dir), 
  436.                     'type'=>$type,
  437.                     'value'=>$value,
  438.                     'exclude_prefix'=>$excludePrefix,
  439.                     'include_prefix'=>$includePrefix,
  440.                     'exclude_sufix'=>$excludeSufix,
  441.                     'include_sufix'=>$includeSufix,
  442.                     'file_extensions'=>$fileExt,
  443.                     'upload'=>$upload,
  444.                     'delete'=>$delete,
  445.                     'create_dirs'=>$createDirs,
  446.                     'allow_none'=>$allowNone),
  447.                 'GBFilePicker session vars - filepicker input = "'.$name.'" ');
  448.         }
  449.         
  450.         return $input.$thumbnail;
  451.     }
  452.     
  453.     
  454.     /**
  455.      * Not part of the module api.
  456.      * Gets the file type of a file.
  457.      * 
  458.      * @param string $file - the path to a file
  459.      * @param string $useMime - set to true to detect file type by mime type
  460.      *
  461.      * @return string - the mime-type or file extension
  462.      */
  463.     function GetFileType($file, $useMime = false) {
  464.         
  465.         $fileType = '';
  466.         if($useMime) {
  467.             if (version_compare(PHP_VERSION, '5.3.0') >= 0 && function_exists('finfo_open')) {
  468.                 $finfo    = finfo_open(FILEINFO_MIME_TYPE); 
  469.                 $fileType = strtolower(finfo_file($finfo, $file));
  470.                 finfo_close($finfo);
  471.             }
  472.             else if(function_exists('mime_content_type')) {
  473.                 $fileType = strtolower(mime_content_type($file));
  474.             }
  475.         }
  476.         else {
  477.             $fileInfo = pathinfo($file);
  478.             $fileType = strtolower($fileInfo['extension']);
  479.         }
  480.         return $fileType;
  481.     }
  482.     
  483.     
  484.     /**
  485.      * Not part of the module api.
  486.      * Create a dropdown form element containing a list of files that match certain conditions
  487.      *
  488.      * @param string $id - the module id
  489.      * @param string $name - the name of the input field
  490.      * @param string $dir - the directory to list the files of (may be relative to uploads dir or absolute path)
  491.      * @param string $selected - the preselected value
  492.      * @param array|string$excludePrefix - fileprefixes to exclude (array('foo','bar',...) or csv)
  493.      * @param array|string$includePrefix - fileprefixes to include (array('foo','bar',...) or csv)
  494.      * @param array|string$excludeSufix - filesufixes to exclude (array('foo','bar',...) or csv)
  495.      * @param array|string$includeSufix - filesufixes to include (array('foo','bar',...) or csv)
  496.      * @param array|string$fileExt - filesufixes to include (array('foo','bar',...) or csv)
  497.      * @param string $type - file or image
  498.      * @param boolean $allowNone - set to false to hide the option 'none'
  499.      *
  500.      * @return string - the HTML output of a select element with options
  501.      */
  502.     function CreateFileDropdown($id, $name, $dir = '', $selected = '', $excludePrefix = '', $includePrefix = '', 
  503.         $excludeSufix = '', $includeSufix = '', $fileExt = '', $type = '', $allowNone = true) 
  504.     {
  505.         
  506.         $files = $this->GetFiles($dir, $excludePrefix, $includePrefix, 
  507.             $excludeSufix, $includeSufix, $fileExt, $type, true);
  508.         
  509.         if(empty($files))
  510.             return;
  511.         
  512.         $dropdown = '<select name="'.$id.$name.'" id="'.$id.$name.'"';
  513.         if($type == 'image')
  514.             $dropdown .= ' onchange="ToggleThumbnail(\'#' . $id.$name . '_GBFilePickerPreviewImage\', jQuery(\'#' . $id.$name . ' option:selected:first\').attr(\'thumbnail\'),this.value,this.value)"';
  515.         
  516.         $dropdown .= '>';
  517.         if( $allowNone )
  518.         {
  519.             $dropdown .= '<option value=""';
  520.             if($selected == '')
  521.                 $dropdown .= ' selected="selected"';
  522.             $dropdown .= ' thumbnail="">--- '.lang('none').' ---</option>';
  523.         }
  524.         
  525.         foreach( $files as $file )
  526.         {
  527.             $dropdown .= '<option value="'.$file['rel_url'].'"';
  528.             if($file['rel_url'] == $selected)
  529.                 $dropdown .= ' selected="selected"';
  530.             if($file['isimage'] && $type == 'image')
  531.                 $dropdown .= ' thumbnail="'.(isset($file['thumburl']) && $file['thumburl']!=''?$file['thumburl']:$file['fullurl']).'"';
  532.             $dropdown .= '>'.$file['basename'].'</option>';
  533.         }
  534.         $dropdown .= "</select>";
  535.         return $dropdown;
  536.     }
  537.     
  538.     
  539.     /**
  540.      * Not part of the module api.
  541.      * Return an array containing a list of files in a directory.
  542.      * Performs a non recursive search.
  543.      *
  544.      * @param string $dir - the directory to list the files of (may be relative to uploads dir or absolute path)
  545.      * @param array|string$excludePrefix - fileprefixes to exclude (array('foo','bar',...) or csv)
  546.      * @param array|string$includePrefix - fileprefixes to include (array('foo','bar',...) or csv)
  547.      * @param array|string$excludeSufix - filesufixes to exclude (array('foo','bar',...) or csv)
  548.      * @param array|string$includeSufix - filesufixes to include (array('foo','bar',...) or csv)
  549.      * @param array|string$fileExt - filesufixes to include (array('foo','bar',...) or csv)
  550.      * @param string $type - file or image
  551.      * @param boolean $excludeDirs - set to true to exclude directories
  552.      *
  553.      * @return array 
  554.      */
  555.     function GetFiles($dir = '', $excludePrefix = '', $includePrefix = '', $excludeSufix = '', 
  556.         $includeSufix = '', $fileExt = '', $type = 'image', $excludeDirs = false) 
  557.     {
  558.         
  559.         global $gCms;
  560.         $files = Array();
  561.         
  562.         $dir = $this->CleanPath($dir);
  563.         $url = $this->CleanURL($dir);
  564.         
  565.         if(!file_exists($dir))
  566.             return $files; // ToDo: return errormessage?
  567.         
  568.         $filePickerstyle = $this->GetPreference('filepickerstyle','both');
  569.         
  570.         if(!is_array($excludePrefix))
  571.             $excludePrefix = $this->CleanArray(explode(',',$excludePrefix));
  572.         
  573.         if(!is_array($includePrefix))
  574.             $includePrefix = $this->CleanArray(explode(',',$includePrefix));
  575.         
  576.         if(!is_array($excludeSufix))
  577.             $excludeSufix = $this->CleanArray(explode(',',$excludeSufix));
  578.         
  579.         if(!is_array($includeSufix))
  580.             $includeSufix = $this->CleanArray(explode(',',$includeSufix));
  581.         
  582.         if(!is_array($fileExt))
  583.             $fileExt = $this->CleanArray(explode(',',$fileExt));
  584.         
  585.         $_fileExt = array('jpg','jpeg','gif','png');
  586.         if($type == 'image') {
  587.             $fileExt = $this->CleanArray(array_intersect($_fileExt, $fileExt));
  588.             if(empty($fileExt))
  589.                 $fileExt = $_fileExt;
  590.         }
  591.         
  592.         $excludePrefix = $this->CleanArray(array_diff($excludePrefix, $includePrefix));
  593.         $excludeSufix  = $this->CleanArray(array_diff($excludeSufix, $includeSufix));
  594.         
  595.         $d = dir($dir);
  596.         while ($entry = $d->read()) {
  597.             if ($entry[0] == '.' || (is_dir($dir.$entry) && $excludeDirs))
  598.                 continue;
  599.             
  600.             $skip         = false;
  601.             $includeThumb = false;
  602.             
  603.             $isDir = is_dir($dir.$entry);
  604.             $file  = pathinfo($dir.$entry);
  605.             
  606.             if(!$isDir) {
  607.                 foreach($excludePrefix as $str) {
  608.                     if(startswith($file['filename'],$str)) {
  609.                         $skip = true;
  610.                         break;
  611.                     }
  612.                 }
  613.                 if($skip) continue;
  614.                 
  615.                 foreach($includePrefix as $str) {
  616.                     if(startswith($str,'thumb_')) {
  617.                         $includeThumb = true;
  618.                     }
  619.                     if(!startswith($file['filename'],$str)) {
  620.                         $skip = true;
  621.                         break;
  622.                     }
  623.                 }
  624.                 if($skip) continue;
  625.                 
  626.                 foreach($excludeSufix as $str) {
  627.                     if(endswith($file['filename'],$str)) {
  628.                         $skip = true;
  629.                         break;
  630.                     }
  631.                 }
  632.                 if($skip) continue;
  633.                 
  634.                 foreach($includeSufix as $str) {
  635.                     if(!endswith($file['filename'],$str)) {
  636.                         $skip = true;
  637.                         break;
  638.                     }
  639.                 }
  640.                 if($skip) continue;
  641.             }
  642.             
  643.             if(startswith($entry,'thumb_') && !$this->GetPreference('showthumbnailfiles',0) && !$includeThumb) {
  644.                 continue;
  645.             }
  646.             
  647.             $fileType = $this->GetFileType($dir.$entry,$this->GetPreference('usemimetype',0));
  648.             if (!$isDir && $type == 'image' && !in_array(str_replace('image/','',$fileType),$fileExt)) {
  649.                 continue;
  650.             }
  651.             else if(!$isDir && $type != 'image' && !in_array($file['extension'],$fileExt) && !empty($fileExt)) {
  652.                 continue;
  653.             }
  654.             
  655.             $file['isimage'] = false;
  656.             if (!$isDir && in_array(str_replace('image/','',$fileType),array('jpg','jpeg','gif','png'))) {
  657.                 $file['isimage'] = true;
  658.             }
  659.             
  660.             $file['fullpath'] = $dir.$entry;
  661.             $file['fullurl']  = $url.$entry;
  662.             $file['rel_url']  = trim(str_replace($gCms->config['uploads_url'],'',$file['fullurl']),'/');
  663.             $file['isdir']    = $isDir;
  664.             $file['type']     = $fileType;
  665.             
  666.             $file['last_modifed'] = filemtime($dir.$entry);
  667.             
  668.             if (!$file['isdir']) {
  669.                 
  670.                 if($file['isimage']) {
  671.                     $file['thumbnail'] = '';
  672.                     $file['thumburl']  = '';
  673.                     if ($filePickerstyle != 'filename') {
  674.                         if ($this->GetPreference('showthumbnailfiles',0) || $includeThumb) {
  675.                             $file['thumbnail'] = $this->GetThumbnail($dir.str_replace('thumb_', '', $entry), $this->GetPreference('makethumbnail',0));
  676.                             $file['thumburl']  = $this->GetThumbnail($dir.str_replace('thumb_', '', $entry), $this->GetPreference('makethumbnail',0),true);
  677.                         } else {
  678.                             $file['thumbnail'] = $this->GetThumbnail($dir.$entry, $this->GetPreference('makethumbnail',0));
  679.                             $file['thumburl']  = $this->GetThumbnail($dir.$entry, $this->GetPreference('makethumbnail',0),true);
  680.                         }
  681.                     }
  682.                     
  683.                     $imgsize = @getimagesize($file['fullpath']);
  684.                     if ($imgsize) {
  685.                         $file['dimensions'] = $imgsize[0] . ' x ' . $imgsize[1];
  686.                     } else {
  687.                         $file['dimensions'] = '&nbsp;';
  688.                     }
  689.                 }
  690.             }
  691.             
  692.             $file['fileicon'] = $this->GetFileIcon($file);
  693.             
  694.             if (!$file['isdir']) {
  695.                 $info = @stat($file['fullpath']);
  696.                 if ($info) {
  697.                     $file['size'] = $info['size'];
  698.                 }
  699.             }
  700.             
  701.             // Debug stuff...
  702.             if($gCms->config['debug']) {
  703.                 $file['debug'] = '<br />';
  704.                 foreach($file as $k=>$v) {
  705.                     if($k != 'debug')
  706.                         $file['debug'] .= "$k : $v<br />";
  707.                 }
  708.             }
  709.             
  710.             $files[] = $file;
  711.         }
  712.         $d->close();
  713.         usort($files, array($this, 'SortFiles'));
  714.         return $files;
  715.     }
  716.     
  717.     
  718.     /**
  719.      * Not part of the module api.
  720.      * Replaces all multiple DIRECTORY_SEPARATOR, dots and (multiple) slashes with one single DIRECTORY_SEPARATOR to make a clean save url parameter
  721.      * 
  722.      * @param string $path - the path to clean
  723.      * @param string $fullPath - true to prepend uploads path on return, false to return only the cleaned $path
  724.      *
  725.      * @return string - the clean path
  726.      */
  727.     function CleanPath($path, $fullPath = true) {
  728.         global $gCms;
  729.         $path = trim(str_replace(array($gCms->config['uploads_path'],$gCms->config['uploads_url']), '', $path),'/'.DIRECTORY_SEPARATOR);
  730.         $path = str_replace(DIRECTORY_SEPARATOR,'/',$path);
  731.         $path = trim(preg_replace('/(\/\.)|(\.\/)|(\/?\.\.\/?)/','/',$path),'./');
  732.         if($fullPath) {
  733.             $path = preg_replace('/[\\/]+/',DIRECTORY_SEPARATOR, '/' . $path . '/');
  734.             $path = $gCms->config['uploads_path'] . $path;
  735.             return $path;
  736.         }
  737.         return trim(preg_replace('/[\\/]+/',DIRECTORY_SEPARATOR, $path) , DIRECTORY_SEPARATOR);
  738.     }
  739.     
  740.     
  741.     /**
  742.      * Not part of the module api.
  743.      * Replaces all multiple slashes, dots and (multiple) backslashes with one single slash to make a clean save url parameter
  744.      * 
  745.      * @param string $url - the url to clean
  746.      * @param string $fullUrl - true to prepend uploads url on return, false to return only the cleaned $url
  747.      *
  748.      * @return string - the clean url
  749.      */
  750.     function CleanURL($url, $fullUrl = true) {
  751.         global $gCms;
  752.         $url = trim(str_replace(array($gCms->config['uploads_path'],$gCms->config['uploads_url']), '', $url),'/'.DIRECTORY_SEPARATOR);
  753.         $url = str_replace(DIRECTORY_SEPARATOR,'/',$url);
  754.         $url = trim(preg_replace('/(\/\.)|(\.\/)|(\/?\.\.\/?)/','/',$url),'./');
  755.         if($fullUrl) {
  756.             $url = preg_replace('/\/+/','/', '/' . str_replace('http://','',$url) . '/');
  757.             $url = $gCms->config['uploads_url'] . $url;
  758.             return $url;
  759.         }
  760.         return trim(preg_replace('/\/+/','/',$url),'/');
  761.     }
  762.     
  763.     
  764.     /**
  765.      * Not part of the module api.
  766.      * Returns the thumbnail of a given image file.
  767.      *
  768.      * @param string $path - the path of the file to create a thumbnail of (can be relative to the uploads dir or absolute)
  769.      * @param string $makeThumbnail - set to false if thumbnail may not be created if not exists
  770.      * @param string $urlOnly - set to true to get only the url to the thumbnail
  771.      *
  772.      * @return string - HTML img element or url
  773.      */
  774.     function GetThumbnail($path, $makeThumbnail = true, $urlOnly = false) {
  775.         if($path == '')
  776.             return false;
  777.         
  778.         global $gCms;
  779.         $fileName = basename($path);
  780.         $image    = '';
  781.         $path     = $this->CleanPath(str_replace($fileName,'',$path));
  782.         $url      = $this->CleanUrl(str_replace($fileName,'',$path));
  783.         
  784.         if (!file_exists($path . 'thumb_' . $fileName) || filemtime($path . $fileName) > filemtime($path . 'thumb_' . $fileName)) {
  785.             if($makeThumbnail) {
  786.                 if(!$this->HandleFileResizing($path . $fileName, $path . 'thumb_' . $fileName, get_site_preference('thumbnail_width', 96), get_site_preference('thumbnail_height',96),true,false,60))
  787.                     return;
  788.             }
  789.             else
  790.                 return;
  791.         }
  792.         if($urlOnly)
  793.             return $url . 'thumb_' . $fileName;
  794.         else
  795.             return '<img class="GBFP_thumbnail" src="' . $url . 'thumb_' . $fileName . '" alt="' . str_replace($gCms->config['uploads_url'],'',$url) . $fileName . '" title="' . str_replace($gCms->config['uploads_url'],'',$url) . $fileName . '" />';
  796.     }
  797.     
  798.     
  799.     /**
  800.      * Not part of the module api.
  801.      * Gets the icon for a file.
  802.      * If FileManager is installed it uses FileManager icons.
  803.      * Otherwise it uses own icons.
  804.      *
  805.      * @param array $fileInfo - an array with info about the file ('ext'=>file extension, 'isdir'=>true/false, isimage=>true/false)
  806.      * @return string - the HTML ouput of an image
  807.      */
  808.     function GetFileIcon($fileInfo) {
  809.         
  810.         if($fileManager =& $this->GetModuleInstance('FileManager')) {
  811.             return $fileManager->GetFileIcon($fileInfo['ext'], $fileInfo['isdir']);
  812.         }
  813.         else {
  814.             if($fileInfo['isdir'])
  815.                 return '<img class="GBFP_fileicon" src="../modules/GBFilePicker/images/dir.gif" title="" alt="" />';
  816.             else if ($fileInfo['isimage'])
  817.                 return '<img class="GBFP_fileicon" src="../modules/GBFilePicker/images/images.gif" title="" alt="" />';
  818.             else
  819.                 return '<img class="GBFP_fileicon" src="../modules/GBFilePicker/images/fileicon.gif" title="" alt="" />';
  820.         }
  821.     }
  822.     
  823.     
  824.     /**
  825.      * Not part of the module api.
  826.      * Gets the icon for the file operation.
  827.      * If FileManager is installed it uses FileManager icons.
  828.      * Otherwise it uses own icons
  829.      *
  830.      * @param string $action - the file operation (e.g. 'delete')
  831.      * @return string - the HTML ouput of an image
  832.      */
  833.     function GetActionIcon($action) {
  834.         
  835.         if($fileManager =& $this->GetModuleInstance('FileManager')) {
  836.             return $fileManager->GetActionIcon($action);
  837.         }
  838.         else {
  839.             return '<img class="GBFP_actionicon" src="../modules/GBFilePicker/images/'.$action.'.gif" title="'.$action.'" alt="'.$action.'" />';
  840.         }
  841.     }
  842.     
  843.     
  844.     /**
  845.      * Not part of the module api.
  846.      * Taken from TinyMCE Module (extracted from filepicker).
  847.      */
  848.     function IsDirEmpty($dir) {
  849.         $d = dir($this->CleanPath($dir));
  850.         while ($entry = $d->read()) {  
  851.             if ($entry == '.') continue;
  852.             if ($entry == '..') continue;
  853.             return false;
  854.         }
  855.         return true;
  856.     }
  857.     
  858.     
  859.     /**
  860.      * Not part of the module api.
  861.      * Taken from TinyMCE filepicker.
  862.      */
  863.     function SortFiles($file1, $file2) {
  864.         if ($file1['isdir'] && !$file2['isdir']) return -1;
  865.         if (!$file1['isdir'] && $file2['isdir']) return 1;
  866.         return strnatcasecmp($file1['basename'], $file2['basename']);
  867.     }
  868.     
  869.     
  870.     /**
  871.      * Not part of the module api.
  872.      * Adapted from TinyMCE filepicker.
  873.      */
  874.     function HandleFileResizing($source, $output, $newWidth, $newHeight, $keepAspectRatio = true, $allowUpscaling = false, $quality = 100) {
  875.         
  876.         $source = $this->CleanPath(str_replace(basename($source),'',$source)).basename($source);
  877.         $output = $this->CleanPath(str_replace(basename($output),'',$output)).basename($output);
  878.         $imgData = @getimagesize($source);
  879.         
  880.         if (!$imgData) 
  881.             return false;
  882.         
  883.         $origImage = '';
  884.         switch($imgData['mime']) {
  885.             case 'image/jpeg': $origImage = @imagecreatefromjpeg($source); break;
  886.             case 'image/gif' : $origImage = @imagecreatefromgif($source); break;
  887.             case 'image/png' : $origImage = @imagecreatefrompng($source); break;
  888.             default: return false;
  889.         }
  890.         $origWidth   = @imagesx($origImage);
  891.         $origHeight  = @imagesy($origImage);
  892.         $aspectRatio = $origWidth / $origHeight;
  893.         
  894.         $newWidth  = floor($newWidth);
  895.         $newHeight = floor($newHeight);
  896.         
  897.         if($newWidth <= 0 && $newHeight > 0) { // force height
  898.             $newWidth = $origWidth;
  899.             if($newHeight > $origHeight && !$allowUpscaling) {
  900.                 $newHeight = $origHeight;
  901.             }
  902.             if($keepAspectRatio) {
  903.                 $newWidth = floor($newHeight * $aspectRatio);
  904.             }
  905.         }
  906.         else if($newHeight <= 0 && $newWidth > 0) { // force width
  907.             $newHeight = $origHeight;
  908.             if($newWidth > $origWidth && !$allowUpscaling) {
  909.                 $newWidth = $origWidth;
  910.             }
  911.             if($keepAspectRatio) {
  912.                 $newHeight = floor($newWidth / $aspectRatio);
  913.             }
  914.         }
  915.         else if($newHeight > 0 && $newWidth > 0) { // both
  916.             if($newWidth > $origWidth && !$allowUpscaling) {
  917.                 $newWidth = $origWidth;
  918.             }
  919.             if($newHeight > $origHeight && !$allowUpscaling) {
  920.                 $newHeight = $origHeight;
  921.             }
  922.             $newAspectRatio = $newWidth / $newHeight;
  923.             if($keepAspectRatio) {
  924.                 
  925.                 if($aspectRatio > 1 && $newAspectRatio < 1) { // landscape to portrait
  926.                     $_tmp = floor($newWidth / $aspectRatio);
  927.                     if($_tmp > 0 && $_tmp <= $newHeight)
  928.                         $newHeight = $_tmp;
  929.                 }
  930.                 else if($aspectRatio < 1 && $newAspectRatio > 1) { // portrait to landscape
  931.                     $_tmp = floor($newHeight * $aspectRatio);
  932.                     if($_tmp > 0 && $_tmp <= $newWidth)
  933.                         $newWidth = $_tmp;
  934.                 }
  935.                 else {
  936.                     if($newAspectRatio < $aspectRatio) {
  937.                         $_tmp = floor($newWidth / $aspectRatio);
  938.                         if($_tmp > 0 && $_tmp <= $newHeight)
  939.                         $newHeight = $_tmp;
  940.                     }
  941.                     else if($newAspectRatio > $aspectRatio) {
  942.                         $_tmp = floor($newHeight * $aspectRatio);
  943.                         if($_tmp > 0 && $_tmp <= $newWidth)
  944.                         $newWidth = $_tmp;
  945.                     }
  946.                 }
  947.             }
  948.         }
  949.         else {
  950.             $newHeight = $origHeight;
  951.             $newWidth  = $origWidth;
  952.         }
  953.         
  954.         if($newWidth < 1)
  955.             $newWidth = 1;
  956.         if($newHeight < 1)
  957.             $newHeight = 1;
  958.         
  959.         $newImage = @imagecreatetruecolor(floor($newWidth), floor($newHeight));
  960.         @imagecopyresampled($newImage, $origImage, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
  961.         switch($imgData['mime']) {
  962.             case 'image/jpeg': return @imagejpeg($newImage, $output, $quality);
  963.             case 'image/gif' : return @imagegif($newImage, $output);
  964.             case 'image/png' : return @imagepng($newImage, $output);
  965.             default          : return false;
  966.         }
  967.         //todo: enable format change?
  968.         /*
  969.         $format = 'unchanged';
  970.         if ($format=='unchanged') {
  971.             switch($imgData['mime']) {
  972.                 case 'image/jpeg': return @imagejpeg($newImage, $output, $quality);
  973.                 case 'image/gif' : return @imagegif($newImage, $output);
  974.                 case 'image/png' : return @imagepng($newImage, $output);
  975.                 default          : return false;
  976.             }
  977.         } else {
  978.             switch ($format) {
  979.                 case 'jpg': return @imagejpeg($newImage, $output, $quality);
  980.                 case 'gif': return @imagegif($newImage, $output);
  981.                 case 'png': return @imagepng($newImage, $output);
  982.                 default   : return;
  983.             }
  984.         }
  985.         */
  986.     }
  987.     
  988.     
  989.     /**
  990.      * Not part of the module api.
  991.      * Taken from TinyMCE Module.
  992.      */
  993.     function ContainsIllegalChars($filename) {
  994.         if (strpos($filename, '\'') !== false) return true;
  995.         if (strpos($filename, '"' ) !== false) return true;
  996.         if (strpos($filename, '/' ) !== false) return true;
  997.         if (strpos($filename, '\\') !== false) return true;
  998.         if (strpos($filename, '&' ) !== false) return true;
  999.         if (strpos($filename, '\$') !== false) return true;
  1000.         if (strpos($filename, '+' ) !== false) return true;
  1001.         return false;
  1002.     }
  1003.     
  1004.     
  1005.     /**
  1006.      * Not part of the module api.
  1007.      * Checks if a var is empty.
  1008.      * If $var is an array it recursivley checks all elements.
  1009.      *
  1010.      * @param mixed $var - the var to check for empty value(s)
  1011.      * @param boolean $trim - true to trim off spaces
  1012.      * @param boolean $unsetEmptyIndexes - true to delete empty elements from array
  1013.      * @return boolean - true if empty, false if not
  1014.      */
  1015.     function IsVarEmpty(&$var, $trim = true, $unsetEmptyIndexes = false) {
  1016.         if (is_array($var)) {
  1017.             foreach ($var as $k=>$v) {
  1018.                 if (!$this->IsVarEmpty($v)) {
  1019.                     return false;
  1020.                 }
  1021.                 else {
  1022.                     if($unsetEmptyIndexes)
  1023.                         unset($var[$k]);
  1024.                     return true;
  1025.                 }
  1026.             }
  1027.         }
  1028.         else if($trim && trim($var) == '') {
  1029.             return true;
  1030.         }
  1031.         else if($var == '') {
  1032.             return true;
  1033.         }
  1034.         return false;
  1035.     }
  1036.     
  1037.     
  1038.     /**
  1039.      * Not part of the module api.
  1040.      * Removes empty elements from an array.
  1041.      * (can be useful when using function explode to create the array from a csv)
  1042.      *
  1043.      * @param array $array - the array to clean up
  1044.      * @return array - an array without empty elements or an empty array
  1045.      */
  1046.     function CleanArray($array) {
  1047.         if (is_array($array)) {
  1048.             foreach ($array as $k=>$v) {
  1049.                 if ($this->IsVarEmpty($v,true,true)) {
  1050.                     unset($array[$k]);
  1051.                 }
  1052.                 else {
  1053.                     if(is_array($v)) {
  1054.                         $v = $this->CleanArray($v);
  1055.                         if($this->IsVarEmpty($v,true,true))
  1056.                             unset($array[$k]);
  1057.                         else
  1058.                             $array[$k] = $v;
  1059.                     }
  1060.                 }
  1061.             }
  1062.             return $array;
  1063.         }
  1064.         return array();
  1065.     }
  1066.     
  1067.     
  1068.     /**
  1069.      * Not part of the module api.
  1070.      * Checks if a value is really meant to be "true".
  1071.      * Can be usefull when checking smarty params for the value true
  1072.      *
  1073.      * @param mixed $value - the value to check
  1074.      * @return bool 
  1075.      */
  1076.     function IsTrue($value) {
  1077.         return (strtolower($value) === 'true' || $value === 1 || $value === '1' || $value === true);
  1078.     }
  1079.     
  1080.     
  1081.     /**
  1082.      * Not part of the module api.
  1083.      * Checks if a value is really meant to be "false".
  1084.      * Can be usefull when checking smarty params for the value false
  1085.      *
  1086.      * @param mixed $value - the value to check
  1087.      * @return bool 
  1088.      */
  1089.     function IsFalse($value) {
  1090.         return (strtolower($value) === 'false' || $value === '0' || $value === 0 || $value === false || $value === '');
  1091.     }
  1092. }
  1093. ?>

Documentation generated on Sun, 05 Sep 2010 21:38:36 +0200 by phpDocumentor 1.4.0a2